import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getUserInfoAPI } from '../../api/user'

// 这个action是可以直接调用的，用来处理异步操作获取数据
export const getUserInfo = createAsyncThunk('user/getUserInfo', async (id) => {
  const res = await getUserInfoAPI(id)
  return res // 此处的返回结果会在 .fulfilled中作为payload的值
})

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    info: {
      id: -1,
      username: '',
      password: '',
      realName: '',
      avatar: '',
      gender: 0,
      email: '',
      mobile: '',
      orgId: '',
      status: 1,
      roleIdList: [],
      postIdList: [],
      superAdmin: 1,
      orgName: '',
      createTime: '',
    },
  },
  reducers: {
    // testUser(state, { payload }) {
    //   state.id = 10001
    //   state.username = 'wuzhengyu458'
    // },
    setUser(state, { payload }) {
      state = { ...state, ...payload }
    },
  },
  extraReducers: {
    // info
    [getUserInfo.pending.type]: (state, { payload }) => {
      // console.log('getUserInfo pending')
    },
    [getUserInfo.fulfilled.type]: (state, { payload }) => {
      console.log('getUserInfo fulfilled', payload.data)
      state.info = { ...payload.data }
    },
    [getUserInfo.rejected.type]: (state, { payload }) => {
      // console.log('getUserInfo rejected', state, payload)
    },
  },
})

// 内置了thunk插件，可以直接处理异步请求
export const asyncTestUser = (payload) => (dispatch) => {
  setTimeout(() => {
    dispatch(testUser(payload))
  }, 2000)
}

// 导出actions
export const { testUser } = userSlice.actions
export default userSlice.reducer // 导出reducer，在创建store时使用到
